<template>
  <div class="user-admin">
    <div class="add-admin">
      <el-button
        @click="addAdmin()"
        type="primary"
        size="small"
        v-if="searchInterface('admins.store')"
      >添加用户</el-button>
    </div>
    <!-- 表格主体 -->
    <el-table :data="adminList" style="width: 100%" border v-loading="loading">
      <el-table-column width="100" label="序号" header-align="center" align="center">
        <template slot-scope="scope">
          <div>{{pages.per_limit*(pages.page-1)+scope.$index+1}}</div>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" prop="name" label="名字" width="150"></el-table-column>
      <el-table-column header-align="center" align="center" prop="account" label="账号" width="150"></el-table-column>
      <el-table-column header-align="center" align="center" prop="email" label="邮箱" width="150"></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="role_name"
        label="对应角色"
        width="150"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="created_at"
        label="添加时间"
        width="180"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="updated_at"
        label="更新时间"
        width="180"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="last_login_at"
        label="上次登录时间"
        width="180"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="current_login_at"
        label="当前登录时间"
        width="180"
      ></el-table-column>
      <el-table-column header-align="center" align="center" label="操作" width="auto">
        <template slot-scope="scope">
          <el-button
            @click="editAdmin(scope.row)"
            type="primary"
            size="small"
            v-if="searchInterface('admins.update')"
            :disabled="scope.row.is_super===1"
          >编辑</el-button>
          <el-button
            type="danger"
            @click="deleteAdmin(scope.row,scope.$index)"
            size="small"
            v-if="searchInterface('admins.destroy')"
            :disabled="scope.row.is_super===1"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="footer">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="pages.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pages.per_limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 弹窗 -->
    <el-dialog :title="(isAdd?'添加':'编辑')+'用户?'" :visible.sync="dialog" width="30%" @close="cancel">
      <el-form ref="form" :rules="rules" :model="admin" label-width="120px" v-if="dialog">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="admin.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model.trim="admin.account" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model.trim="admin.password" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model.trim="admin.email" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否开启？" prop="is_enable">
          <el-switch v-model="admin.is_enable" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>

        <el-form-item label="选择角色" prop="role_id">
          <el-select v-model="admin.role_id" placeholder="请选择角色">
            <el-option v-for="{id,name} in roleList" :label="name" :value="id" :key="id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAdminList,
  addAdmin,
  editAdmin,
  deleteAdmin
} from '@/api/user-center/admin'
import { getAllRole } from '@/api/user-center/role'
import { check, date } from '@/utils'
// 账号中心-用户管理
export default {
  data() {
    const that = this
    const checkPassword = (rule, value, callback) => {
      if (that.isAdd) {
        if (!value) {
          callback('请输入密码')
        } else {
          if (check.isNumAndAZ(value)) {
            callback()
          } else {
            callback('密码格式不对，需由数字和字母组成（不区分大小写6-10）')
          }
        }
      } else {
        if (value) {
          if (check.isNumAndAZ(value)) {
            callback()
          } else {
            callback('密码格式不对，需由数字和字母组成（不区分大小写6-10）')
          }
        } else {
          callback()
        }
      }
    }
    const checkAccount = (rule, value, callback) => {
      if (!value) {
        callback('请输入账号')
      } else {
        callback()
      }
    }
    const checkEmail = (rule, value, callback) => {
      if (value) {
        if (check.isEmail(value)) {
          callback()
        } else {
          callback('邮箱格式不对')
        }
      } else {
        callback()
      }
    }
    const checkRole = (rule, value, callback) => {
      if (!value) {
        callback('请选择角色')
      } else {
        callback()
      }
    }
    return {
      loading: false,
      isGetRole: false,
      adminList: [],
      pages: {
        page: 1,
        per_limit: 10
      },
      total: 0,
      roleList: [],
      isAdd: true,
      dialog: false,
      admin: {
        name: '',
        account: '',
        password: '',
        email: '',
        is_enable: true,
        role_id: ''
      },
      rules: {
        name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
        account: [{ required: true, validator: checkAccount, trigger: 'blur' }],
        password: [
          { required: true, validator: checkPassword, trigger: 'blur' }
        ],
        email: [{ validator: checkEmail, trigger: 'blur' }],
        role_id: [{ required: true, validator: checkRole, trigger: 'change' }]
      }
    }
  },
  beforeMount() {
    this.getAdminList()
  },
  methods: {
    // 获取管理员列表
    getAdminList() {
      this.loading = true
      getAdminList(this.pages)
        .then(res => {
          const { data, total } = res
          data.forEach(i => {
            i.created_at = date.formatDate(i.created_at)
            i.updated_at = date.formatDate(i.updated_at)
            i.last_login_at = date.formatDate(i.last_login_at)
            i.current_login_at = date.formatDate(i.current_login_at)
          })
          this.adminList = data
          this.total = total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取所有角色
    getAllRole() {
      getAllRole().then(res => {
        this.roleList = res
      })
    },
    // 新增用户
    addAdmin() {
      this.dialog = true
      this.isAdd = true
      this.admin = {
        name: '',
        account: '',
        password: '',
        email: '',
        is_enable: true,
        role_id: ''
      }
      this.iSGetRoleReuest()
    },
    // 是否请求获取角色
    iSGetRoleReuest() {
      if (!this.isGetRole) {
        this.getAllRole()
        this.isGetRole = true
      }
    },
    // 编辑用户
    editAdmin(data) {
      this.iSGetRoleReuest()
      this.dialog = true
      this.isAdd = false
      const { name, account, password, email, is_enable, role_id, id } = data
      this.admin = {
        name,
        account,
        password,
        email,
        id,
        is_enable: is_enable === 1 ? true : false,
        role_id
      }
    },
    // 取消
    cancel(formName = 'form') {
      this.$refs[formName].resetFields()
      this.dialog = false
    },
    // 删除用户
    deleteAdmin({ id }, index) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户操作？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAdmin(id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 直接删除当前数据
            this.adminList.splice(index, 1)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 提交
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const {
            name,
            account,
            password,
            email,
            is_enable,
            role_id,
            id
          } = this.admin
          const params = { name, account, password, email, is_enable, role_id }
          params.is_enable = is_enable ? 1 : 0
          if (this.isAdd) {
            addAdmin(params).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              // 这里之所以再次调用，是因为数据需要的id是后台生成，
              // 如果直接push进去数据，会导致没办法删除该用户，因为删除依赖于id
              this.getAdminList()
              this.cancel()
            })
          } else {
            editAdmin({ params, id }).then(() => {
              this.$message({
                type: 'success',
                message: '编辑成功!'
              })
              // 如果编辑直接替换当前数据
              const adminList = this.adminList
              const item = adminList.find(i => i.id === id)
              Object.assign(item, params)
              item.password = ''
              this.adminList = adminList
              this.cancel()
            })
          }
        }
      })
    },
    // 切换页码
    currentChange(value) {
      this.pages.page = value
      this.getAdminList()
    },
    sizeChange(value) {
      this.pages.per_limit = value
      this.getAdminList()
    }
  }
}
</script>

<style lang="scss" scoped>
.user-admin {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
  .add-admin {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
  }
  .footer {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>